package com.dominator.serviceImpl;

import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.mybatis.dao.T_accountPO;
import com.dominator.mybatis.dao.T_userDao;
import com.dominator.mybatis.dao.T_userPO;
import com.dominator.repository.DaoAccount;
import com.dominator.repository.DaoUser;
import com.dominator.service.ApiSmsService;
import com.dominator.service.ApiUserService;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.encode.Des3Utils;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.system.PropertiesLoader;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApiUserServiceImpl implements ApiUserService{

    public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");

    @Autowired
    DaoAccount accountDao;

    @Autowired
    ApiSmsService apiSmsService;

    @Autowired
    DaoUser userDao;
    @Autowired
    T_userDao tUserDao;



    @Override
    public ApiMessage updateUser(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "phoneNum");
        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(user)) {
            log.error("用户不存在");
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        if (SystemUtils.isNotEmpty(dto.getString("headImg"))){
            user.setHead_img(dto.getString("headImg"));
        }
        if (SystemUtils.isNotEmpty(dto.getString("nickName"))){
            user.setNick_name(dto.getString("nickName"));
        }
        if (SystemUtils.isNotEmpty(dto.getString("genter"))){
            user.setGenter(dto.getString("genter"));
        }
        if (SystemUtils.isNotEmpty(dto.getString("email"))){
            user.setEmail(dto.getString("email"));
        }
        if (SystemUtils.isNotEmpty(dto.getString("birthday"))){
            user.setBirthday(dto.getDate("birthday"));
        }

        userDao.updateByPrimaryKey(user);
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage bindingPhone(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage bindingWxOpenId(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "wxOpenId,phoneNum");
        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(user)) {
            log.error("用户不存在");
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        if (dto.getString("wxOpenId").equals(user.getWx_open_id())){
            log.error("用户已绑定");
            throw new ApiException(ReqEnums.WECHAT_OPENID_IS_BINDING);
        }
        T_userPO wxUser = userDao.selectByWxOpenId(dto.getString("wxOpenId"));
        if (SystemUtils.isNotEmpty(wxUser)) {
            log.error("已存在指定微信用户");
            throw new ApiException(ReqEnums.WECHAT_OPENID_IS_EXSIT);
        }
        user.setWx_open_id(dto.getString("wxOpenId"));
        tUserDao.updateByKey(user);
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage bindingQq(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage bindingWeixin(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage bindingWeibo(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public ApiMessage modifyPassword(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "phoneNum,password,newPasswword");
        T_userPO user = userDao.selectByPhoneNumPassword(dto.getString("phoneNum"), dto.getString("password"));
        if (SystemUtils.isEmpty(user)) {
            log.error("密码错误");
            throw new ApiException(ReqEnums.REQ_WRONG_PASSWORD);
        }
        user.setPassword(Des3Utils.encode(dto.getString("newPassword")));
        userDao.updateByPrimaryKey(user);
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage findPassword(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "phoneNum,verifyCode,password");
        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(user)) {
            log.error("用户不存在");
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        // 校验验证码是否存在
        dto.put("verifyType", 3);
        apiSmsService.verifySms(dto);
        user.setPassword(Des3Utils.encode(dto.getString("password")));
        userDao.updateByPrimaryKey(user);
        return ApiMessageUtil.success();

    }



    @Override
    public ApiMessage getUser(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "phoneNum");
        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
        if (SystemUtils.isEmpty(user)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        // 查询账户 如果没有账户给添加一个
        T_accountPO account = accountDao.selectByUserId(user.getId());
        if (SystemUtils.isEmpty(account)) {
            accountDao.createAccount(user);
            account = accountDao.selectByUserId(user.getId());
        }
        Dto outDto = Dtos.newDto();
        outDto.put("phoneNum", SystemUtils.isEmpty(user.getPhone_num()) ? "" : user.getPhone_num());
        outDto.put("nickName", SystemUtils.isEmpty(user.getNick_name()) ? "" : user.getNick_name());
        outDto.put("headImg", SystemUtils.isEmpty(user.getHead_img()) ? "" : user.getHead_img());
        outDto.put("genter", SystemUtils.isEmpty(user.getGenter()) ? "" : user.getGenter());
        outDto.put("id", SystemUtils.isEmpty(user.getId()) ? "" : user.getId());
        outDto.put("points", SystemUtils.isEmpty(account.getPoints()) ? 0 : account.getPoints());
        outDto.put("money",SystemUtils.isEmpty(account.getMoney())?0:account.getMoney());
        outDto.put("birthday", SystemUtils.isEmpty(user.getBirthday()) ? "" : user.getBirthday());
        outDto.put("email", SystemUtils.isEmpty(user.getEmail()) ? "" : user.getEmail());
        outDto.put("memberGrade",SystemUtils.isEmpty(user.getMember_grade()) ? "1" : user.getMember_grade());
        if(SystemUtils.isNotEmpty(user.getMember_grade_effect_time())){
            outDto.put("memberGradeEfTime",user.getMember_grade_effect_time());
        }
        return ApiMessageUtil.success(outDto);

    }

    @Override
    public ApiMessage invitationList(Dto dto) throws ApiException {
        // TODO Auto-generated method stub
        return null;
    }



    @Override
    public ApiMessage getUserQRCode(Dto dto) throws ApiException {
//        ApiMessage msg = new ApiMessage();
//        ApiUtils.checkToken(dto.getString("phoneNum"), dto.getString("token"));
//        T_userPO user = userDao.selectByPhoneNum(dto.getString("phoneNum"));
//        if (SystemUtils.isEmpty(user)) {
//            throw new ApiException(Constants.REQ_PARAM_ERROR, "用户不存在");
//        }
//        String qrCode = "";
//        if (SystemUtils.isEmpty(user.getQr_img())) {
//            String text = propertiesLoader.getProperty("USER_QRCODE_FRONT") + "?phoneNum="
//                    + dto.getString("phoneNum");
//            try {
//                qrCode = QRCodeUtil.encode(text, propertiesLoader.getProperty("qrcode.logo.path"), true);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            if (ApiUtils.objIsNotEmpty(qrCode)) {
//                T_userPO users = new T_userPO();
//                users.setId(user.getId());
//                users.setQr_img(qrCode);
//                userDao.updateByPrimaryKey(users);
//                msg.setCode(Constants.REQ_SUCCESS);
//                msg.setMessage(Constants.MSG_SUCCESS);
//            } else {
//                msg.setCode(Constants.SYS_ERROR);
//                msg.setMessage("二维码生成失败");
//            }
//        } else {
//            msg.setCode(Constants.REQ_SUCCESS);
//            msg.setMessage(Constants.MSG_SUCCESS);
//            qrCode = user.getQr_img();
//        }
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("qrImg", qrCode);
//        msg.setData(Des3Utils.encResponse(map));
        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage upgrade(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"userId,upgrade");
        T_userPO user = userDao.selectByPrimaryKey(dto.getString("userId"));
        if (SystemUtils.isEmpty(user)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        String memberGrade = SystemUtils.isEmpty(user.getMember_grade())?"1":user.getMember_grade();
        if(dto.getInteger("upgrade")<=Integer.parseInt(memberGrade)){
            throw new ApiException(ReqEnums.USER_IS_UPGRADED_LOW);
        }
        user.setMember_grade_effect_time(ApiUtils.getNextYear(new Date()));
        user.setMember_grade(dto.getString("upgrade"));
        userDao.updateByPrimaryKey(user);

        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage renewal(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"userId");
        T_userPO user = userDao.selectByPrimaryKey(dto.getString("userId"));
        if (SystemUtils.isEmpty(user)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }

        user.setMember_grade_effect_time(ApiUtils.getNextYear(user.getMember_grade_effect_time()));
        userDao.updateByPrimaryKey(user);

        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage upgradeNoTime(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"userId,upgrade");
        T_userPO user = userDao.selectByPrimaryKey(dto.getString("userId"));
        if (SystemUtils.isEmpty(user)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        String memberGrade = SystemUtils.isEmpty(user.getMember_grade())?"1":user.getMember_grade();
        if(dto.getInteger("upgrade")<=Integer.parseInt(memberGrade)){
            throw new ApiException(ReqEnums.USER_IS_UPGRADED_LOW);
        }
        user.setMember_grade(dto.getString("upgrade"));
        userDao.updateByPrimaryKey(user);

        return ApiMessageUtil.success();
    }

    @Override
    public ApiMessage getUserByOpenId(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"wxOpenId");
        T_userPO user = userDao.selectByWxOpenId(dto.getString("wxOpenId"));
        if (SystemUtils.isEmpty(user)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        // 查询账户 如果没有账户给添加一个
        T_accountPO account = accountDao.selectByUserId(user.getId());
        if (SystemUtils.isEmpty(account)) {
            accountDao.createAccount(user);
            account = accountDao.selectByUserId(user.getId());
        }
        Dto outDto = Dtos.newDto();
        outDto.put("phoneNum", SystemUtils.isEmpty(user.getPhone_num()) ? "" : user.getPhone_num());
        outDto.put("nickName", SystemUtils.isEmpty(user.getNick_name()) ? "" : user.getNick_name());
        outDto.put("headImg", SystemUtils.isEmpty(user.getHead_img()) ? "" : user.getHead_img());
        outDto.put("genter", SystemUtils.isEmpty(user.getGenter()) ? "" : user.getGenter());
        outDto.put("id", SystemUtils.isEmpty(user.getId()) ? "" : user.getId());
        outDto.put("userId", SystemUtils.isEmpty(user.getId()) ? "" : user.getId());
        outDto.put("points", SystemUtils.isEmpty(account.getPoints()) ? 0 : account.getPoints());
        outDto.put("money",SystemUtils.isEmpty(account.getMoney())?0:account.getMoney());
        outDto.put("birthday", SystemUtils.isEmpty(user.getBirthday()) ? "" : user.getBirthday());
        outDto.put("email", SystemUtils.isEmpty(user.getEmail()) ? "" : user.getEmail());
        outDto.put("memberGrade",SystemUtils.isEmpty(user.getMember_grade()) ? "1" : user.getMember_grade());
        if(SystemUtils.isNotEmpty(user.getMember_grade_effect_time())){
            outDto.put("memberGradeEfTime",user.getMember_grade_effect_time());
        }
        outDto.put("real_name",SystemUtils.isEmpty(user.getReal_name()) ? "" : user.getReal_name());
        outDto.put("id_card",SystemUtils.isEmpty(user.getId_card()) ? "" : user.getId_card());

        return ApiMessageUtil.success(outDto);

    }

    @Override
    public ApiMessage editRealName(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "wxOpenId");
        T_userPO user = userDao.selectByWxOpenId(dto.getString("wxOpenId"));
        if (SystemUtils.isEmpty(user)) {
            log.error("用户不存在");
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }
        if (SystemUtils.isNotEmpty(dto.getString("real_name"))){
            user.setReal_name(dto.getString("real_name"));
        }
        if (SystemUtils.isNotEmpty(dto.getString("id_card"))){
            user.setId_card(dto.getString("id_card"));
        }
        userDao.updateByPrimaryKey(user);
        return ApiMessageUtil.success();
    }

    @Override
    public T_userPO getUserById(String userId) throws ApiException {
        T_userPO tUserPO = tUserDao.selectByKey(userId);
        if (SystemUtils.isEmpty(tUserPO)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        } else if ("0".equals(tUserPO.getIs_valid())) {
            throw new ApiException(ReqEnums.REQ_USER_IS_NOT_VALID);
        }
        return tUserPO;
    }

    @Override
    public T_userPO getUserByPhoneNum(String phoneNum) throws ApiException{
        T_userPO tUserPO = userDao.selectByPhoneNum(phoneNum);
        if (SystemUtils.isEmpty(tUserPO)) {
            throw new ApiException(ReqEnums.REQ_USER_NOT_EXSIT);
        }else if ("0".equals(tUserPO.getIs_valid())) {
            throw new ApiException(ReqEnums.REQ_USER_IS_NOT_VALID);
        }
        return tUserPO;
    }

    @Override
    public T_userPO getUserByDto(Dto dto) throws ApiException{
        T_userPO tUserPO =new T_userPO();
        if(SystemUtils.isNotEmpty(dto.getString("userId"))){
            tUserPO=getUserById(dto.getString("userId"));
        }else if (SystemUtils.isNotEmpty(dto.getString("phoneNum"))){
            tUserPO=getUserByPhoneNum(dto.getString("phoneNum"));
        }else if (SystemUtils.isNotEmpty(dto.getString("wxOpenId"))){
            tUserPO= userDao.selectByWxOpenId(dto.getString("wxOpenId"));
        }
        if ("0".equals(tUserPO.getIs_valid())) {
            throw new ApiException(ReqEnums.REQ_USER_IS_NOT_VALID);
        }
        return tUserPO;
    }
}
